package com.mo.axion.service.api.impl.action.send;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Throwables;
import com.mo.axion.common.domain.SimpleTaskInfo;
import com.mo.axion.common.domain.TaskInfo;
import com.mo.axion.common.enums.RespStatusEnum;
import com.mo.axion.common.pipeline.BusinessProcess;
import com.mo.axion.common.pipeline.ProcessContext;
import com.mo.axion.common.vo.BasicResultVO;
import com.mo.axion.service.api.impl.domain.SendTaskModel;
import com.mo.axion.support.mq.SendMqService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Mo
 * @createTime 2024/2/24 23:57
 * @description 发送消息
 */
@Slf4j
@Service
public class SendMqAction implements BusinessProcess<SendTaskModel> {

    @Autowired
    private SendMqService sendMqService;

    @Value("${axion.business.topic.name}")
    private String sendMessageTopic;

    @Value("${axion.mq.pipeline}")
    private String mqPipeline;

    /**
     * 真正处理逻辑
     *
     * @param context
     */
    @Override
    public void process(ProcessContext<SendTaskModel> context) {
        SendTaskModel sendTaskModel = context.getProcessModel();
        List<TaskInfo> taskInfoList = sendTaskModel.getTaskInfoList();
        try {
            String message = JSON.toJSONString(sendTaskModel.getTaskInfoList(), new SerializerFeature[]{SerializerFeature.WriteClassName});
            sendMqService.send(sendMessageTopic, message);
            context.setResponse(
                    BasicResultVO.success(taskInfoList.stream().map(
                            v -> SimpleTaskInfo.builder()
                                    .businessId(v.getBusinessId())
                                    .messageId(v.getMessageId())
                                    .bizId(v.getBizId())
                                    .build()).collect(Collectors.toList())
                    )
            );
        } catch (Exception e) {
            context.setIsNeedBreak(true)
                    .setResponse(BasicResultVO.fail(RespStatusEnum.SERVICE_ERROR));
            log.error("send {} fail! e:{}, params: {}", mqPipeline, Throwables.getStackTraceAsString(e), JSON.toJSONString(CollUtil.getFirst(taskInfoList.listIterator())));
        }
    }
}
